import type { XmlType } from '@/services/global/type';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import { Button, message, Modal } from 'antd';
import { useState } from 'react';
import { getPreviewUrl } from '@/utils/utils';

type Props = {
  xmlPath: string;
  xmlHistory: XmlType[];
  urlProp?: string;
};

const XmlPreview: React.FC<Props> = ({ xmlPath, xmlHistory, urlProp = 'albumXmlPath' }) => {
  const [modalVisible, setModalVisible] = useState(false);

  const columns: ProColumns<XmlType>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '更新日期',
      dataIndex: 'uploadTime',
    },
    {
      title: 'XML',
      dataIndex: urlProp,
      render: (_, record) => {
        return (
          <a href={getPreviewUrl(record[urlProp])} target="_blank">
            xml文件
          </a>
        );
      },
    },
  ];

  const handleOpenXml = () => {
    if (xmlHistory && xmlHistory.length > 0) {
      setModalVisible(true);
      return;
    }

    if (xmlPath) {
      window.open(getPreviewUrl(xmlPath), '_blank');
    } else {
      message.error('XML不存在');
    }
  };

  return (
    <>
      <Button type="link" className="linkBtn" disabled={!xmlPath} onClick={handleOpenXml}>
        XML
      </Button>
      {modalVisible && (
        <Modal
          title="查看XML文件"
          visible={true}
          onCancel={() => {
            setModalVisible(false);
          }}
        >
          <ProTable<XmlType>
            columns={columns}
            dataSource={xmlHistory}
            rowKey="albumId"
            pagination={false}
            toolBarRender={false}
            search={false}
          />
        </Modal>
      )}
    </>
  );
};

export default XmlPreview;
